package com.luobu.javaee.service;

import com.luobu.javaee.dao.ArchiveMapper;
import com.luobu.javaee.dao.ArchiveShareMapper;
import com.luobu.javaee.dao.DocumentMapper;
import com.luobu.javaee.dao.UserMapper;
import com.luobu.javaee.domain.Archive;
import com.luobu.javaee.domain.Document;
import com.luobu.javaee.domain.User;
import com.luobu.javaee.domain.dto.DocumentDto;
import com.luobu.javaee.domain.dto.DocumentResDto;
import com.luobu.javaee.exception.DocumentException;
import com.luobu.javaee.util.FileIO;
import com.luobu.javaee.util.FileDelete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DocumentService {
    @Autowired
    DocumentMapper documentMapper;

    @Autowired
    ArchiveShareMapper archiveShareMapper;

    @Autowired
    ArchiveMapper archiveMapper;

    @Autowired
    UserMapper userMapper;

    String host;
    @Value("${server.port}")
    String post;                  // 主机端口

    /**
     * @description 添加文档
     * @param 
     * @throws DocumentException
     */
    public void addDoc(DocumentDto documentDto) throws DocumentException, IOException
    {
        Document document = documentDto.getDocument();
        if(document.getArchiveId() == null)
            document.setArchiveId(-1L);
        Long userId = document.getUserId();
        String docName = document.getDocName();
        Long archiveId = document.getArchiveId();
        List<Document> documents = documentMapper.findByUserIdAndDocNameAndArchiveId(userId, docName, archiveId);
        if(!documents.isEmpty())
        {
            throw new DocumentException(
                    "不可在同一个文集下面插入同名文件");
        }
        documentMapper.insert(document);

        // 将文档内容写入磁盘
        String filePath = FileIO.getFilePath(userId, docName, archiveId);
        String docContent = documentDto.getContent();
        FileIO.resourcePathCheck(filePath);
        FileIO.writeFile(filePath, docContent);

        // 为该文档新建图片文件夹
        docName = docName.replaceAll("\\.", "_");
        filePath = FileIO.getPictureDirPath(userId, docName, document.getArchiveId());
        FileIO.resourceDirCheck(filePath);
    }

    public void updateDoc(DocumentDto documentDto) throws DocumentException, IOException
    {
        Document document = documentDto.getDocument();
        Long userId = document.getUserId();
        String docName = document.getDocName();
        Long archiveId = document.getArchiveId();

        // 将文档内容写入磁盘
        String filePath = FileIO.getFilePath(userId, docName, archiveId);
        String docContent = documentDto.getContent();
        FileIO.resourcePathCheck(filePath);
        FileIO.writeFile(filePath, docContent);
    }

    /**
     * @description 为一个文档添加Base64型式的图片
     * @param
     * @throws DocumentException
     */
    /*
    public void addDocPictureBase64(DocumentDto documentDto)
    {
        int i = 0;
        String docName = documentDto.getDocument().getDocName();
        Long userId = documentDto.getDocument().getUserId();
        for (String str : documentDto.getPictures())
        {
            i++;
            String filePath = FileIO.getPicturePath(userId, docName, (long) i);
            FileIO.writeFile(filePath, str);
        }
    }
    */


    /**
     * @description 删除文档
     * @param
     * @throws DocumentException
     */
    public void deleteDoc(Long id) throws DocumentException, IOException {
        Document document = documentMapper.selectById(id);
        System.out.println("数据库查找完毕:");
        System.out.println(document);
        if(document == null) {
            throw new DocumentException(
                    "no file in table");
        }
        // 删除文件
        Long userId = document.getUserId();
        String filepath = FileIO.getFilePath(userId, document.getDocName(), document.getArchiveId());
        System.out.println("删除路径："+filepath);
        boolean flag = FileDelete.deleteFiles(filepath);
        if (!flag){
            throw new DocumentException("FileDelete.deleteFiles wrong");
        }
        String picDirPath = FileIO.getPictureDirPath(userId, document.getDocName(), document.getArchiveId());
        flag = FileDelete.deleteDiretory(picDirPath);
        // 删除数据库中的记录
        documentMapper.deleteById(id);
    }

    public List<DocumentResDto> getUserArchiveDoc(Long userId, Long archiveId) throws DocumentException, IOException {
        if(archiveId == null)
            archiveId = -1L;
        List<DocumentResDto> documentResDtos = new ArrayList<>();
        String archivePath = FileIO.getFileArchivePath(userId, archiveId);
        File archive = new File(archivePath);
        if (!archive.exists() || !archive.isDirectory())
            return documentResDtos;
        File[] docFiles = archive.listFiles();
        for (File docFile : docFiles) {

            DocumentResDto documentResDto = new DocumentResDto();
            if (docFile.isFile()) {
                String fileName = docFile.getName();
                documentResDto.setDocName(fileName);

                // 读取文件内容并将内容添加到documentResDto中
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(docFile));
                    StringBuilder content = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        content.append(line).append("\n");
                    }
                    reader.close();
                    documentResDto.setDocContent(content.toString());

                    List<Document> userDoc = documentMapper.findByUserIdAndDocNameAndArchiveId(userId, fileName, archiveId);
                    if(userDoc.isEmpty())
                        continue;
                    Long docId = userDoc.get(0).getId();
                    documentResDto.setDocId(docId);
                    documentResDto.setDocArchiveId(archiveId);

                } catch (IOException e) {
                    throw new DocumentException("无法读取文件内容：" + e.getMessage());
                }

                documentResDtos.add(documentResDto);
            } else {
                throw new DocumentException("非法文件");
            }
        }

        return documentResDtos;
    }

    public List<DocumentResDto> getList(String userName) throws DocumentException, IOException {
        Long userId = Long.valueOf(userMapper.selectByUsername(userName).getId());
        String userDirPath = FileIO.getUserDocDir(userId);
        File userDir = new File(userDirPath);

        System.out.println("获取文件路径："+userDirPath);

        List<DocumentResDto> documentResDtos = new ArrayList<>();

        // 检查目录是否存在
        if (userDir.exists() && userDir.isDirectory()) {
            // 获取目录中的所有文件
            File[] archives = userDir.listFiles();
            if (archives != null) {
                for (File archive : archives) {
                    String archiveFileName = archive.getName();
                    Long archiveId = archiveFileName.equals("default") ? -1L : Long.parseLong(archiveFileName);
                    File[] docFiles = archive.listFiles();
                    for (File docFile : docFiles) {

                        DocumentResDto documentResDto = new DocumentResDto();
                        if (docFile.isFile()) {
                            String fileName = docFile.getName();
                            documentResDto.setDocName(fileName);

                            // 读取文件内容并将内容添加到documentResDto中
                            try {
                                BufferedReader reader = new BufferedReader(new FileReader(docFile));
                                StringBuilder content = new StringBuilder();
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    content.append(line).append("\n");
                                }
                                reader.close();
                                documentResDto.setDocContent(content.toString());

                                List<Document> userDoc = documentMapper.findByUserIdAndDocNameAndArchiveId(userId, fileName, archiveId);
                                if(userDoc.isEmpty())
                                    continue;
                                Long docId = userDoc.get(0).getId();
                                documentResDto.setDocId(docId);
                                documentResDto.setDocArchiveId(archiveId);

                            } catch (IOException e) {
                                throw new DocumentException("无法读取文件内容：" + e.getMessage());
                            }

                            documentResDtos.add(documentResDto);
                        } else {
                            throw new DocumentException("非法文件");
                        }
                    }
                }
            } else {
                throw new DocumentException("目录不存在");
            }
        }

        return documentResDtos;
    }

    public List<Archive> getShareList(String userName) throws DocumentException, IOException {
//        List<DocumentResDto> documentResDtos = new ArrayList<>();
//        List<Long> archiveIds = archiveShareMapper.selectArchiveIdByUserId(userId);
//
//        for (Long archiveId : archiveIds) {
//            List<DocumentResDto> res = archiveService.searchArchive(archiveId);
//            documentResDtos.addAll(res);
//        }
//
//        return documentResDtos;

        User user = userMapper.selectByUsername(userName);
        if (user == null) {
            return new ArrayList<>();
        }

        List<Long> archiveIds = archiveShareMapper.selectArchiveIdByUserId(Long.valueOf(user.getId()));

        List<Archive> archives = new ArrayList<>();
        for (Long archiveId : archiveIds) {
            Archive archive = archiveMapper.selectById(archiveId);
            archives.add(archive);
        }

        return archives;
        // return archiveShareMapper.selectArchiveIdByUserId(Long.valueOf(userMapper.selectByUsername(userName).getId()));
    }

    public void shareArchives(List<Long> archiveIds, String userName) throws DocumentException, IOException {
        Long userId = Long.valueOf(userMapper.selectByUsername(userName).getId());
        for (Long archiveId : archiveIds) {

            List<Long> res = archiveMapper.findArchiveIdByArchiveId(archiveId);

            if (res.isEmpty()) {
                throw new DocumentException("文集不存在");
            }
            archiveShareMapper.insert(archiveId, userId);
        }
    }

    void updateDocument(Document document) {
        documentMapper.deleteByDocNameAndUserId(document.getDocName(), document.getUserId());
        documentMapper.insert(document);
    }
}
